﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using MessageRouter.Configuration;
using System.Diagnostics;

namespace MessageRouter.Msmq
{
    public sealed class MsmqMessageWriter : MessageWriter
    {
        private readonly MessageQueue messageQueue;
        private readonly MsmqEndpointAddress endpointAddress;

        public MsmqMessageWriter(WriterConfigurationElement config)
            : base(config)
        {
            this.endpointAddress = new MsmqEndpointAddress(base.Address);

            string connectionString = GetConnectionString(endpointAddress);

            this.messageQueue = new MessageQueue(connectionString);
            this.messageQueue.DefaultPropertiesToSend.Recoverable = true;
        }

        public override void Close()
        {
            this.messageQueue.Close();
        }

        public override void OnNext(RoutedMessage routedMessage)
        {
            try
            {
                Message msmqMessage = new Message(routedMessage.MessageBody);
                this.messageQueue.Send(msmqMessage, routedMessage.MessageId.ToString(), MessageQueueTransactionType.Automatic);
            }
            catch (Exception ex)
            {
                Trace.TraceError("MsmqMessageWriter failed with error: {0}", ex.Message);
                throw;
            }
        }

        private string GetConnectionString(MsmqEndpointAddress endpointAddress)
        {
            return string.Format(@"{0}\{1}", endpointAddress.ServerName, endpointAddress.QueueName);
        }
    }
}
